//
//  AkeyConfigurationVC.m
//  sensen_ios
//
//  Created by mc on 16/3/9.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "AkeyConfigurationVC.h"


#import "DeviceListVC.h"
//model
#import "DeviceInfo.h"

//View
#import "NewUITextField.h"

//功能
#import "LANFindServer.h"
#import "AQWifiConfig.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import "getgateway.h"
#import "Reachability.h"
#import "NetConnectInfo.h"

#define CONFIG_TIME 60


@interface AkeyConfigurationVC ()<UITextFieldDelegate, UIAlertViewDelegate>{
    DeviceInfo *_deviceInfo;
    UIImageView *gifImageView;
}

@property (strong, nonatomic) NSString *ssid;
@property (strong, nonatomic) NSTimer *timer;
@property (strong, nonatomic) AQWifiConfig *aqWifiConfig;
@property (strong, nonatomic) LANFindServer *lanFindServer;
@property (nonatomic) NSInteger timerCount;
@property (strong, nonatomic) UIProgressView *progressView;

@end

@implementation AkeyConfigurationVC



@synthesize ssid = _ssid;
@synthesize progressView = _progressView;
@synthesize timer = _timer;
@synthesize aqWifiConfig = _aqWifiConfig;
@synthesize lanFindServer = _lanFindServer;
@synthesize timerCount = _timerCount;



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"无线局域网设置";
    
    [self _initView];
    
    
    NSLog(@"%@", [self fetchSSIDInfo]);
    _ssid = [[self fetchSSIDInfo] objectForKey:@"SSID"];
    UITextField * textField = (UITextField *)[self.view viewWithTag:100];
    textField.text = _ssid;
     _timerCount = 0;
    
    
    [self _initGitView];
    // Do any additional setup after loading the view.
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];

    [self  cancelConfigPressed:nil];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    if ([SVProgressHUD isVisible]) {
        [SVProgressHUD dismissAfterDelay:2];

    }


}



- (void)_initView{
    [self _initBackgroundView];
    [self _initHeaderView];
    [self _initUITextFieldView];
    [self _initButtonView];
}


-(void)_initGitView{
    gifImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    gifImageView.hidden = YES;
    
    
    CGFloat x = 100;
    CGFloat y = 70;
    CGFloat width = 0;
    CGFloat height = 20;
    
    
    UILabel *title = [[UILabel alloc] init];
    title.text = @"连接鱼保姆";
    title.textColor = SS_NAVI_BLUE_COLOR;
    title.textAlignment = NSTextAlignmentCenter;
    [gifImageView addSubview:title];
    [title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(gifImageView).offset(25);
        make.centerX.equalTo(gifImageView.mas_centerX).offset(0);
        make.size.mas_equalTo(CGSizeMake(120, 25));
    }];
    
    
    gifImageView.userInteractionEnabled = YES;
    UILabel *normalLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    normalLabel.font = FONT(12);
    normalLabel.text = @"正在为您努力连接中 , ";
    normalLabel.textColor = SS_NAVI_BLUE_COLOR;
    normalLabel.textAlignment = NSTextAlignmentCenter;
    [gifImageView addSubview:normalLabel];
    // 设置宽度
    normalLabel.width = [normalLabel.text getSizeOfString:12].width;
    
    x = normalLabel.right;
    UILabel *  tapCancelLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    tapCancelLabel.userInteractionEnabled = YES;
    tapCancelLabel.font = FONT(14);
    tapCancelLabel.text = @"取消本次连接";
    tapCancelLabel.textColor = SS_NAVI_BLUE_COLOR;
    tapCancelLabel.textAlignment = NSTextAlignmentCenter;
    [gifImageView addSubview:tapCancelLabel];
    // 设置宽度
    tapCancelLabel.width = [tapCancelLabel.text getSizeOfString:14].width;
    
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:tapCancelLabel.text];
    // 下划线
    [attrString addAttribute:NSUnderlineStyleAttributeName
                       value:@1
                       range:NSMakeRange(0, tapCancelLabel.text.length)];
    tapCancelLabel.attributedText = attrString;

    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelAction:)];
    [tapCancelLabel addGestureRecognizer:tap];
    
    
    NSData  *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"设备匹配中" ofType:@"gif"]];
    UIImage *gif = [UIImage sd_animatedGIFWithData:data];
    gifImageView.image = gif;
    [self.view addSubview:gifImageView];
}

- (void)gitPlay{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    for (UIView *view in self.view.subviews) {
        view.hidden = YES;
    }
    [self.view endEditing:YES];
    gifImageView.hidden = NO;
}
-(void)gitRemoveFromSuperview{
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    for (UIView *view in self.view.subviews) {
        view.hidden = NO;
    }
    gifImageView.hidden = YES;
}



- (void)_initHeaderView{
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    header.backgroundColor = rgba(201, 202, 203, 1);
    [self.view addSubview:header];
    UILabel *lable = [[UILabel alloc] init];
    [header addSubview:lable];
    lable.text = @"一键配置";
    [lable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(header).offset(20);
        make.top.equalTo(header).offset(0);
        make.bottom.equalTo(header).offset(0);
        make.width.equalTo(@200);
    }];
    
}


- (void)_initUITextFieldView{
    NSArray * array = @[@"网络名称", @"无线密码"];
    CGFloat height = 40;
    CGFloat interval  = 3;
    for (int i = 0; i < 2; i++) {
        NewUITextField * textField = [[NewUITextField alloc] initWithFrame:CGRectMake(0, 0, 0, height)];
        textField.headLabel.text = array[i];
        textField.textField.tag = 100 + i;
        textField.textField.delegate = self;
        if (i == 0) {
            textField.frame = CGRectMake(0, 30, SCREEN_WIDTH, height);
            textField.textField.placeholder = @"网络名称";
        }else if (i == 1){
            UILabel * lable = [[UILabel alloc] initWithFrame:CGRectMake(0, 30 + height, SCREEN_WIDTH, interval)];
            [self.view addSubview:lable];
            lable.backgroundColor = [UIColor whiteColor];
            textField.frame = CGRectMake(0, 30 + height + interval, SCREEN_WIDTH, height);
            textField.textField.placeholder = @"输入密码";
            textField.textField.secureTextEntry = YES;
            _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, textField.bottom + 10, SCREEN_WIDTH, 5)];
            _progressView.progressTintColor = SS_DEVICE_BLUE_COLOR;
            [self.view addSubview:_progressView];

        }
        [self.view addSubview:textField];
        
    }
    
    
}




- (void)_initBackgroundView{
    
    UIImageView * backgroundImage = [[UIImageView alloc] init];
    backgroundImage.image = [UIImage imageNamed:@"手动添加设备_03"];
    [self.view addSubview:backgroundImage];
    [backgroundImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.bottom.equalTo(self.view.mas_bottom).offset(-50);
        make.size.mas_equalTo(CGSizeMake(240, 240));
        
    }];
    self.view.backgroundColor = SS_NAVI_GRAY_COLOR;
    
}



- (void)_initButtonView{
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 160, SCREEN_WIDTH, 40)];
    [self.view addSubview:footer];
    
    
    // 创建确定按钮
    UIButton  * determineBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [footer addSubview:determineBtn];
    [determineBtn setTitle:@"确定" forState:UIControlStateNormal];
    [determineBtn addTarget:self action:@selector(determineAction:) forControlEvents:UIControlEventTouchUpInside];
    [determineBtn setBackgroundColor:SS_DEVICE_BLUE_COLOR];
    determineBtn.layer.borderColor = SS_DEVICE_BLUE_COLOR.CGColor;
    determineBtn.layer.borderWidth = 1;
    determineBtn.layer.masksToBounds = YES;
    determineBtn.layer.cornerRadius = 3.0;
    
    
    // 创建取消按钮
    UIButton  * cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [footer addSubview:cancelBtn];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTintColor:[UIColor blackColor]];
    [cancelBtn addTarget:self action:@selector(cancelAction:) forControlEvents:UIControlEventTouchUpInside];
    [cancelBtn setBackgroundColor:[UIColor clearColor]];
    cancelBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    cancelBtn.layer.borderWidth = 1;
    cancelBtn.layer.masksToBounds = YES;
    cancelBtn.layer.cornerRadius = 3.0;
    
    [determineBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(footer).offset(50);
        make.centerY.equalTo(footer.mas_centerY);
        make.height.equalTo(@30);
        make.height.equalTo(cancelBtn);
        make.right.equalTo(cancelBtn.mas_left).offset(-20);
        make.width.equalTo(cancelBtn);
    }];
    
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(footer).offset(-50);
        make.centerY.equalTo(footer.mas_centerY);
        make.height.equalTo(@30);
        
    }];
    
}



- (void)determineAction:(UIButton *)button{
   [self.view endEditing:YES];
    
   
    UITextField * textField1 = (UITextField *)[self.view viewWithTag:100];
    UITextField * textField2 = (UITextField *)[self.view viewWithTag:101];
    
    NSString * ssid = [textField1.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    NSString * pwd =  [textField2.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    NSLog(@"网络名称%@", ssid);
    NSLog(@"无线密码%@", pwd);
    
    
    if ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != ReachableViaWiFi)
    {
        UIAlertView *noWiFiAlert = [[UIAlertView alloc] initWithTitle:@"请先连接WiFi"
                                                              message:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"确定"
                                                    otherButtonTitles:nil, nil];
        [noWiFiAlert setTag:1];
        [noWiFiAlert show];
        return;
    }
    
    if ([[textField1 text] isEqualToString:@""])
    {
        [[[UIAlertView alloc] initWithTitle:@"请输入SSID"
                                    message:nil
                                   delegate:nil
                          cancelButtonTitle:@"确定"
                          otherButtonTitles:nil, nil] show];
        return;
    }
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1
                                              target:self
                                            selector:@selector(timerUpdate:)
                                            userInfo:nil
                                             repeats:YES];
    [_timer fire];
    NSString *myIP = [[[NetConnectInfo alloc] init] LocalWiFiIPAddress];
    NSString *gatewayIP = [[[NetConnectInfo alloc] init] GetConfigAddress];
    
    NSLog(@"IP ＝ %@  gateway = %@", myIP, gatewayIP);
    
    [self gitPlay];

    [self.aqWifiConfig Start:ssid key:pwd  gwip: gatewayIP];
    
    [self.lanFindServer Start];
    __weak typeof (self) weakSelf = self;
    [self.lanFindServer setNewDeviceCallback:^(WifiDevice *obj)
     {
         
//         NSLog(@"设备信息 ＝ %@", [obj description]);
         _deviceInfo = [[DeviceInfo alloc] initWithDid:obj.m_did
                                                       macAddress:obj.m_mac
                                                         password:obj.m_password
                                                               ip:obj.m_lanIp
                                                                                                                                                  isLock:obj.m_lock];
         
         
        
         
         //检测是否已经存在，已经存在忽略不计
         NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];
         id object =  [userDefault objectForKey:SENSEN_DEVICE_AQ];
         
         if (object != nil&&  [object respondsToSelector:@selector(initWithCoder:)]&& [object isKindOfClass:NSData.class]) {
             
             NSData * customData = (NSData * )object;
             NSMutableArray *  array = [NSKeyedUnarchiver unarchiveObjectWithData:customData];
             
             //列表存在，该设备不存在
             if (array.count > 0 &&  ![weakSelf isThisDeviceExist:_deviceInfo :array]) {
                
                 
                 
                 [weakSelf cancelConfigPressed:nil];
                 [weakSelf gitRemoveFromSuperview];
                 UIAlertView *findDeviceAlert = [[UIAlertView alloc] initWithTitle:@"发现新设备"
                                                                           message:nil
                                                                          delegate:weakSelf
                                                                 cancelButtonTitle:@"添加"
                                                                 otherButtonTitles:nil, nil];
                 [findDeviceAlert setTag:2];
                 [findDeviceAlert show];

              //列表为空
             }else if (array.count == 0){
                 
                 
                 [weakSelf cancelConfigPressed:nil];
                 [weakSelf gitRemoveFromSuperview];
                 UIAlertView *findDeviceAlert = [[UIAlertView alloc] initWithTitle:@"发现新设备"
                                                                           message:nil
                                                                          delegate:weakSelf
                                                                 cancelButtonTitle:@"添加"
                                                                 otherButtonTitles:nil, nil];
                 [findDeviceAlert setTag:2];
                 [findDeviceAlert show];

                 
             }
           
             
          //缓存失败的时候
         }else{
             
             
             [weakSelf cancelConfigPressed:nil];
             [weakSelf gitRemoveFromSuperview];
             UIAlertView *findDeviceAlert = [[UIAlertView alloc] initWithTitle:@"发现新设备"
                                                                       message:nil
                                                                      delegate:weakSelf
                                                             cancelButtonTitle:@"添加"
                                                             otherButtonTitles:nil, nil];
             [findDeviceAlert setTag:2];
             [findDeviceAlert show];

             
             
         }
         
         
    }];
}


#pragma -mark- 是否已经存在
- (BOOL)isThisDeviceExist:(DeviceInfo *)deviceInfo :(NSMutableArray *)array{
    
    for (DeviceInfo *tempDevice in array)
    {
        if ([deviceInfo.did isEqualToString:tempDevice.did])
        {
            deviceInfo.name = tempDevice.name;
            return YES;
        }
    }
    return NO;
}





- (void)requestAddDevice:(DeviceInfo *)deviceInfo{

    if (!deviceInfo.name) {
        deviceInfo.name = @"新设备";
    }
    if ( deviceInfo.did == nil || deviceInfo.did.length == 0 ) {
        [SVProgressHUD showOnlyStatus:@"设备解析出错，设备ID为空" withDuration:2];
        return;
    }
    
    if (deviceInfo.password == nil || deviceInfo.password.length == 0) {
                [[[UIAlertView alloc] initWithTitle:@"添加失败"
                                            message:@"该设备已被锁定，请解锁后添加"
                                           delegate:nil
                                  cancelButtonTitle:@"确定"
                                  otherButtonTitles:nil, nil] show];
        return;
    }

    
    
    
    NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];
    id object =  [userDefault objectForKey:SENSEN_DEVICE_AQ];
    
    if (object != nil&&  [object respondsToSelector:@selector(initWithCoder:)]&& [object isKindOfClass:NSData.class]) {
        NSData * customData = (NSData * )object;
        NSMutableArray *  array = [NSKeyedUnarchiver unarchiveObjectWithData:customData];
        
        if (array.count > 0) {
            
            if ([self isThisDeviceExist:deviceInfo WithArray:array]) {
                
                for (DeviceInfo *tempDevice in array)
                {
                    if ([deviceInfo.did isEqualToString:tempDevice.did])
                    {
                        if (tempDevice.password.length > 0 && (deviceInfo.password.length == 0|| deviceInfo.password == nil)) {
                            [[[UIAlertView alloc] initWithTitle:@"添加失败"
                                                        message:@"设备已存在，无需添加，由于该设备已被锁定，重新添加会导致无法连接"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil, nil] show];
                            return;
                        }
                        
                    }
                }

            }
            

        }
    
    }
    
    if (deviceInfo.password.length == 0 || deviceInfo.password == nil) {
        [SVProgressHUD showOnlyStatus:@"密码为空" withDuration:3];
        return;
    }
    DeviceListVC *deviceListVC = (DeviceListVC *)[self.navigationController.viewControllers objectAtIndex:0];
    [deviceListVC addDevice:deviceInfo];
    [SVProgressHUD showSuccessWithStatus:@"添加成功" withDuration:1];
    [self cancelConfigPressed:nil];
    [self.navigationController popViewControllerAnimated:YES];
    
}


- (BOOL)isThisDeviceExist:(DeviceInfo *)deviceInfo WithArray:(NSMutableArray *)array{
    
    for (DeviceInfo *tempDevice in array)
    {
        if ([deviceInfo.did isEqualToString:tempDevice.did])
        {
            deviceInfo.name = tempDevice.name;
            return YES;
        }
    }
    return NO;
}




- (void)cancelConfigPressed:(id)sender
{
    
    
    [self.aqWifiConfig Stop];
    [self.lanFindServer Stop];
    [_timer invalidate];
    [_progressView setProgress:0];
    _timerCount = 0;
}


- (void)timerUpdate:(NSTimer *)timer
{
    
    _timerCount++;
    float progress = _timerCount / (float)CONFIG_TIME;
    [_progressView setProgress: progress animated:YES];
    
    if (_timerCount >= CONFIG_TIME)
    {
        [self uploadLog];
        [_timer invalidate];
        _timerCount = 0;
        [self cancelConfigPressed:nil];
        [self  gitRemoveFromSuperview];
        [[[UIAlertView alloc] initWithTitle:@"配置超时"
                                    message:@"请尝试重新开始配置"
                                   delegate:nil
                          cancelButtonTitle:@"确定"
                          otherButtonTitles:nil, nil] show];
    }
//    NSLog(@"timerCount = %ld", (long)_timerCount);
}


//上报信息, 用于定位用户一键配置的问题
-(void) uploadLog{
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    if (_deviceInfo) {
        if (_deviceInfo.did) {
            [dictionary setObject:_deviceInfo.did forKey:@"did"];
        }
        
        if (_deviceInfo.password) {
            [dictionary setObject:_deviceInfo.password forKey:@"password"];
        }
        
    }
    [ByLogCollector uploadLinkDeviceTimeoutLog:dictionary];
}


- (void)cancelAction:(UIButton *)button{
    [self.view endEditing:YES];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController popViewControllerAnimated:YES];
}



#pragma -mark- Setter and Getter
- (AQWifiConfig *)aqWifiConfig
{
    if (nil == _aqWifiConfig)
    {
        _aqWifiConfig = [[AQWifiConfig alloc] init];
    }
    return _aqWifiConfig;
}

- (LANFindServer *)lanFindServer
{
    if (nil == _lanFindServer)
    {
        _lanFindServer = [[LANFindServer alloc] init];
    }
    return _lanFindServer;
}

- (id)fetchSSIDInfo
{
    NSArray *ifs = (__bridge_transfer NSArray *)CNCopySupportedInterfaces();
    NSDictionary *info;
    for (NSString *ifnam in ifs)
    {
        info = (__bridge_transfer NSDictionary *)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        if (info && [info count]) { break; }
    }
    return info;
}

#pragma -mark- UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (0 == buttonIndex)
    {
        if (alertView.tag == 2)
        {
            [self gitRemoveFromSuperview];
            [self requestAddDevice:_deviceInfo];
           // [self.navigationController popViewControllerAnimated:YES];
        }
        else if(alertView.tag == 1)
        {
            BOOL canOpenSettings = (&UIApplicationOpenSettingsURLString != NULL);
            if (canOpenSettings) {
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:url];
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}



#pragma  mark --- textFieldDelegate ---

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
  
    if (textField.tag == 100)
    {
        [textField becomeFirstResponder];
        return NO;
    }
    else if (textField.tag == 101)
    {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}


-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
